import {
  ArrowLeftOutlined,
  AudioOutlined,
  CodeOutlined,
  DesktopOutlined, // 新增：执行文件图标
  FileExcelOutlined,
  FileImageOutlined,
  FileOutlined,
  FilePdfOutlined,
  FilePptOutlined,
  FileTextOutlined,
  FileWordOutlined,
  FileZipOutlined,
  FolderOutlined,
  VideoCameraOutlined
} from '@ant-design/icons'
import { Button, Input, List, Spin } from 'antd'
import { message } from 'antd'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

interface FileSearchResult {
  path: string
  name: string
  highlightedName?: string
  highlightedPath?: string
  isFolder: boolean
  size?: number
  dateModified?: string
  icon?: string // 新增：文件图标路径
}

interface FileSearchScreenProps {
  onClose: () => void
}

enum FileCategory {
  ALL = 'all',
  FOLDER = 'folder',
  EXECUTABLE = 'executable', // 确保包含执行文件分类
  WORD = 'word',
  EXCEL = 'excel',
  PPT = 'ppt',
  PDF = 'pdf',
  IMAGE = 'image',
  VIDEO = 'video',
  AUDIO = 'audio'
}

// 文件分类函数
const FileSearchScreen: React.FC<FileSearchScreenProps> = ({ onClose }) => {
  useTranslation('fileSearch')
  const [searchText, setSearchText] = useState('')
  const [results, setResults] = useState<FileSearchResult[]>([])
  const [loading, setLoading] = useState(false)
  const [hasSearched, setHasSearched] = useState(false)
  const [activeCategory, setActiveCategory] = useState<FileCategory>(FileCategory.ALL)

  // 文件分类函数
  const getFileCategory = (fileName: string, isFolder: boolean): FileCategory[] => {
    if (isFolder) return [FileCategory.ALL, FileCategory.FOLDER]

    const ext = fileName.toLowerCase().split('.').pop() || ''
    const categories = [FileCategory.ALL]

    if (['doc', 'docx'].includes(ext)) {
      categories.push(FileCategory.WORD)
    } else if (['xls', 'xlsx'].includes(ext)) {
      categories.push(FileCategory.EXCEL)
    } else if (['ppt', 'pptx'].includes(ext)) {
      categories.push(FileCategory.PPT)
    } else if (['pdf'].includes(ext)) {
      categories.push(FileCategory.PDF)
    } else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'raw'].includes(ext)) {
      categories.push(FileCategory.IMAGE)
    } else if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', 'm4v', '3gp'].includes(ext)) {
      categories.push(FileCategory.VIDEO)
    } else if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus'].includes(ext)) {
      categories.push(FileCategory.AUDIO)
    } else if (['exe', 'msi', 'bat', 'cmd', 'com', 'scr', 'app', 'deb', 'rpm', 'dmg'].includes(ext)) {
      categories.push(FileCategory.EXECUTABLE) // 新增：执行文件分类逻辑
    }

    return categories
  }

  // 过滤结果函数
  const getFilteredResults = () => {
    if (activeCategory === FileCategory.ALL) {
      return results
    }
    return results.filter((result) => getFileCategory(result.name, result.isFolder).includes(activeCategory))
  }

  // 获取分类计数
  const getCategoryCount = (category: FileCategory) => {
    if (category === FileCategory.ALL) {
      return results.length
    }
    return results.filter((result) => getFileCategory(result.name, result.isFolder).includes(category)).length
  }

  // 获取文件图标
  const getFileIcon = (fileName: string, isFolder: boolean, iconPath?: string) => {
    if (isFolder) {
      return <FolderOutlined style={{ color: '#1890ff', fontSize: '16px' }} />
    }

    const ext = fileName.toLowerCase().split('.').pop() || ''
    const iconStyle = { fontSize: '16px' }

    // 如果是执行文件且有图标路径，显示真实图标
    if (['exe', 'msi', 'app'].includes(ext) && iconPath) {
      return (
        <img
          src={iconPath}
          style={{ width: '16px', height: '16px' }}
          alt="应用图标"
          onError={(e) => {
            // 图标加载失败时显示默认图标
            e.currentTarget.style.display = 'none'
            e.currentTarget.nextElementSibling?.setAttribute('style', 'display: inline')
          }}
        />
      )
    }

    if (['doc', 'docx'].includes(ext)) {
      return <FileWordOutlined style={{ ...iconStyle, color: '#2b579a' }} />
    } else if (['xls', 'xlsx'].includes(ext)) {
      return <FileExcelOutlined style={{ ...iconStyle, color: '#217346' }} />
    } else if (['ppt', 'pptx'].includes(ext)) {
      return <FilePptOutlined style={{ ...iconStyle, color: '#d24726' }} />
    } else if (['pdf'].includes(ext)) {
      return <FilePdfOutlined style={{ ...iconStyle, color: '#ff4d4f' }} />
    } else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico', 'tiff', 'raw'].includes(ext)) {
      return <FileImageOutlined style={{ ...iconStyle, color: '#722ed1' }} />
    } else if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm', 'm4v', '3gp'].includes(ext)) {
      return <VideoCameraOutlined style={{ ...iconStyle, color: '#fa541c' }} />
    } else if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma', 'm4a', 'opus'].includes(ext)) {
      return <AudioOutlined style={{ ...iconStyle, color: '#13c2c2' }} />
    } else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
      return <FileZipOutlined style={{ ...iconStyle, color: '#fa8c16' }} />
    } else if (['txt', 'md', 'log'].includes(ext)) {
      return <FileTextOutlined style={{ ...iconStyle, color: '#52c41a' }} />
    } else if (
      [
        'js',
        'ts',
        'jsx',
        'tsx',
        'html',
        'css',
        'json',
        'xml',
        'py',
        'java',
        'cpp',
        'c',
        'cs',
        'php',
        'go',
        'rs',
        'swift',
        'kt'
      ].includes(ext)
    ) {
      return <CodeOutlined style={{ ...iconStyle, color: '#1890ff' }} />
    } else if (['exe', 'msi', 'bat', 'cmd', 'com', 'scr', 'app', 'deb', 'rpm', 'dmg'].includes(ext)) {
      return <DesktopOutlined style={{ ...iconStyle, color: '#f5222d' }} />
    }

    return <FileOutlined style={{ ...iconStyle, color: '#8c8c8c' }} />
  }

  // 防抖搜索
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debounceSearch = useCallback(
    (() => {
      let timeoutId: NodeJS.Timeout
      return (searchValue: string) => {
        clearTimeout(timeoutId)
        timeoutId = setTimeout(() => {
          handleSearch(searchValue)
        }, 300)
      }
    })(),
    []
  )

  // ESC键监听
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [onClose])

  // 搜索函数
  // 搜索函数
  const handleSearch = async (searchValue: string) => {
    if (!searchValue.trim()) {
      setResults([])
      setHasSearched(false)
      return
    }

    setLoading(true)
    setHasSearched(true)

    try {
      // 增加搜索结果数量限制，获取更多文件
      const searchResults = await window.api.everything.search(searchValue, 1000)

      // 对结果进行排序，优先显示exe文件
      const sortedResults = (searchResults || []).sort((a, b) => {
        const aExt = a.name.toLowerCase().split('.').pop() || ''
        const bExt = b.name.toLowerCase().split('.').pop() || ''

        // exe文件优先
        const aIsExe = aExt === 'exe'
        const bIsExe = bExt === 'exe'

        if (aIsExe && !bIsExe) return -1
        if (!aIsExe && bIsExe) return 1

        // 其他可执行文件次优先
        const executableExts = ['msi', 'bat', 'cmd', 'com', 'scr']
        const aIsExecutable = executableExts.includes(aExt)
        const bIsExecutable = executableExts.includes(bExt)

        if (aIsExecutable && !bIsExecutable) return -1
        if (!aIsExecutable && bIsExecutable) return 1

        // 按文件名排序
        return a.name.localeCompare(b.name)
      })

      setResults(sortedResults)
    } catch (error) {
      console.error('搜索文件时出错:', error)
      message.error('搜索失败，请重试')
      setResults([])
    } finally {
      setLoading(false)
    }
  }

  // 输入框值改变事件
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setSearchText(value)
    debounceSearch(value)
  }

  // 点击搜索结果项
  const handleItemClick = async (item: FileSearchResult) => {
    try {
      // 使用 openPath 打开本地文件
      await window.api.openPath(item.path)
      // 移除 onClose() - 不再自动关闭搜索界面
    } catch (error) {
      console.error('打开文件时出错:', error)
      message.error('无法打开文件')
    }
  }

  // 分类按钮点击处理
  const handleCategoryClick = (category: FileCategory) => {
    setActiveCategory(category)
  }

  const filteredResults = getFilteredResults()

  return (
    <ScreenContainer>
      {/* 顶部标题栏 */}
      <Header>
        <BackButton onClick={onClose}>
          <ArrowLeftOutlined /> 返回
        </BackButton>
        <Title>文件搜索</Title>
      </Header>

      {/* 搜索框 */}
      <SearchContainer>
        <SearchInput
          placeholder="请输入搜索关键词"
          value={searchText}
          onChange={handleInputChange}
          size="large"
          autoFocus
        />
      </SearchContainer>

      {/* 主要内容区域 */}
      <MainContent>
        {/* 左侧分类面板 */}
        <CategoryPanel>
          <CategoryTitle>文件分类</CategoryTitle>
          <CategoryList>
            <CategoryButton
              $active={activeCategory === FileCategory.ALL}
              onClick={() => handleCategoryClick(FileCategory.ALL)}>
              全部 ({getCategoryCount(FileCategory.ALL)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.EXECUTABLE}
              onClick={() => handleCategoryClick(FileCategory.EXECUTABLE)}>
              执行文件 ({getCategoryCount(FileCategory.EXECUTABLE)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.FOLDER}
              onClick={() => handleCategoryClick(FileCategory.FOLDER)}>
              文件夹 ({getCategoryCount(FileCategory.FOLDER)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.WORD}
              onClick={() => handleCategoryClick(FileCategory.WORD)}>
              Word ({getCategoryCount(FileCategory.WORD)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.EXCEL}
              onClick={() => handleCategoryClick(FileCategory.EXCEL)}>
              Excel ({getCategoryCount(FileCategory.EXCEL)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.PPT}
              onClick={() => handleCategoryClick(FileCategory.PPT)}>
              PPT ({getCategoryCount(FileCategory.PPT)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.PDF}
              onClick={() => handleCategoryClick(FileCategory.PDF)}>
              PDF ({getCategoryCount(FileCategory.PDF)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.IMAGE}
              onClick={() => handleCategoryClick(FileCategory.IMAGE)}>
              图片 ({getCategoryCount(FileCategory.IMAGE)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.VIDEO}
              onClick={() => handleCategoryClick(FileCategory.VIDEO)}>
              视频 ({getCategoryCount(FileCategory.VIDEO)})
            </CategoryButton>
            <CategoryButton
              $active={activeCategory === FileCategory.AUDIO}
              onClick={() => handleCategoryClick(FileCategory.AUDIO)}>
              音频 ({getCategoryCount(FileCategory.AUDIO)})
            </CategoryButton>
          </CategoryList>
        </CategoryPanel>

        {/* 右侧结果面板 */}
        <ResultsPanel>
          <ResultsHeader>
            <h3>搜索结果</h3>
            {hasSearched && <span>共找到 {filteredResults.length} 个结果</span>}
          </ResultsHeader>
          <ResultsContainer>
            {loading ? (
              <LoadingContainer>
                <Spin size="large" />
                <p>搜索中...</p>
              </LoadingContainer>
            ) : (
              <StyledList
                dataSource={filteredResults}
                renderItem={(item) => (
                  <List.Item
                    onClick={() => handleItemClick(item as FileSearchResult)}
                    style={{ cursor: 'pointer', padding: '12px 16px' }}>
                    <List.Item.Meta
                      avatar={getFileIcon((item as FileSearchResult).name, (item as FileSearchResult).isFolder)}
                      title={
                        <div
                          dangerouslySetInnerHTML={{
                            __html: (item as FileSearchResult).highlightedName || (item as FileSearchResult).name
                          }}
                        />
                      }
                      description={
                        <div
                          dangerouslySetInnerHTML={{
                            __html: (item as FileSearchResult).highlightedPath || (item as FileSearchResult).path
                          }}
                        />
                      }
                    />
                  </List.Item>
                )}
                locale={{
                  emptyText: hasSearched ? '未找到相关文件' : '请输入关键词开始搜索'
                }}
              />
            )}
          </ResultsContainer>
        </ResultsPanel>
      </MainContent>
    </ScreenContainer>
  )
}

// 样式组件

// 主容器 - 全屏布局
const ScreenContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100vh; /* 全屏高度 */
  width: 100vw; /* 全屏宽度 */
  background: var(--color-background);
  overflow: hidden;
`

// 顶部标题栏 - 添加拖拽功能
const Header = styled.div`
  display: flex;
  align-items: center;
  padding: 12px 16px; /* 标题栏内边距：上下12px，左右16px */
  border-bottom: 1px solid var(--color-border);
  background: var(--color-background);
  z-index: 10;
  -webkit-app-region: drag; /* 启用窗口拖拽功能 */
`

// 返回按钮 - 禁用拖拽以保持按钮可点击
const BackButton = styled(Button)`
  display: flex;
  align-items: center;
  gap: 8px; /* 图标与文字间距 */
  border: none;
  background: transparent;
  color: var(--color-text);
  padding: 4px 8px; /* 按钮内边距 */
  -webkit-app-region: no-drag; /* 禁用拖拽，保持按钮可点击 */

  &:hover {
    background: var(--color-background-soft);
    color: var(--color-primary);
  }
`

// 标题文字
const Title = styled.h2`
  margin: 0 0 0 16px; /* 左边距16px */
  font-size: 18px; /* 标题字体大小 */
  font-weight: 600;
  color: var(--color-text);
  -webkit-app-region: no-drag; /* 如果标题需要选择文本，禁用拖拽 */
`

// 搜索框容器
const SearchContainer = styled.div`
  padding: 16px; /* 搜索框区域内边距 */
  border-bottom: 1px solid var(--color-border);
  background: var(--color-background);
`

// 搜索输入框
const SearchInput = styled(Input)`
  border-radius: 8px; /* 搜索框圆角 */

  .ant-input {
    border-radius: 8px;
  }
`

// 主内容区域 - 左右分栏布局
const MainContent = styled.div`
  display: flex;
  flex: 1;
  overflow: hidden;
`

// 左侧分类面板
const CategoryPanel = styled.div`
  width: 150px; /* 分类面板宽度 - 可调整 */
  border-right: 1px solid var(--color-border);
  background: var(--color-background-soft);
  overflow-y: auto;
  flex-shrink: 0;
`

// 分类面板标题
const CategoryTitle = styled.h4`
  margin: 0;
  padding: 16px; /* 分类标题内边距 */
  font-size: 14px; /* 分类标题字体大小 */
  font-weight: 600;
  color: var(--color-text-secondary);
  border-bottom: 1px solid var(--color-border);
`

// 分类按钮列表容器
const CategoryList = styled.div`
  padding: 8px; /* 分类列表内边距 */
`

// 分类按钮
const CategoryButton = styled.div<{ $active: boolean }>`
  display: block;
  width: 100%;
  padding: 8px 12px; /* 分类按钮内边距：上下8px，左右12px */
  margin-bottom: 4px; /* 按钮间距 */
  border: none;
  border-radius: 6px; /* 按钮圆角 */
  background: ${(props) => (props.$active ? 'var(--color-primary-opacity)' : 'transparent')};
  color: ${(props) => (props.$active ? 'var(--color-primary)' : 'var(--color-text)')};
  font-size: 13px; /* 分类按钮字体大小 */
  cursor: pointer;
  transition: all 0.2s;
  text-align: left;

  &:hover {
    background: var(--color-primary-opacity);
    color: var(--color-primary);
  }
`

// 右侧结果面板
const ResultsPanel = styled.div`
  flex: 1; /* 占据剩余空间 */
  display: flex;
  flex-direction: column;
  overflow: hidden;
`

// 结果面板标题栏
const ResultsHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px; /* 结果标题栏内边距 */
  border-bottom: 1px solid var(--color-border);
  background: var(--color-background);

  h3 {
    margin: 0;
    font-size: 14px; /* 结果标题字体大小 */
    font-weight: 600;
    color: var(--color-text);
  }

  span {
    font-size: 13px; /* 结果统计字体大小 */
    color: var(--color-text-secondary);
  }
`

// 结果列表容器
const ResultsContainer = styled.div`
  flex: 1;
  overflow: hidden;
`

// 结果列表样式
const StyledList = styled(List)`
  height: 100%;
  overflow-y: auto;

  .ant-list-item {
    border-bottom: 1px solid var(--color-border-light);
    transition: background-color 0.2s;

    &:hover {
      background-color: var(--color-background-soft);
    }
  }

  .ant-list-item-meta-title {
    margin-bottom: 4px; /* 文件名与路径间距 */
    font-size: 14px; /* 文件名字体大小 */
    font-weight: 500;

    mark {
      background-color: var(--color-primary-opacity);
      color: var(--color-primary);
      padding: 1px 2px; /* 高亮文字内边距 */
      border-radius: 2px; /* 高亮文字圆角 */
    }
  }

  .ant-list-item-meta-description {
    font-size: 12px; /* 文件路径字体大小 */
    color: var(--color-text-secondary);

    mark {
      background-color: var(--color-primary-opacity);
      color: var(--color-primary);
      padding: 1px 2px;
      border-radius: 2px;
    }
  }
`

// 加载状态容器
const LoadingContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px; /* 加载区域高度 */

  p {
    margin-top: 16px; /* 加载文字与图标间距 */
    color: var(--color-text-secondary);
  }
`

export default FileSearchScreen
